package client

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"

	"gitee.com/zh-jn/harmonica-previewer-online/api"
)

func NewSideCarClient(addr string, port int) *SidecarClient {
	return &SidecarClient{
		Addr: addr,
		Port: port,
		c:    &http.Client{},
	}
}

type SidecarClient struct {
	Addr string
	Port int

	c *http.Client
}

func (c *SidecarClient) SetJsBundle(jsbundleId, sessionId string, reader io.Reader) error {
	rsp, err := c.c.Post(fmt.Sprintf("http://%v:%v/?jsbundleid=%v&sessionid=%v", c.Addr, c.Port, jsbundleId, sessionId), "", reader)
	if err != nil {
		return err
	}
	if rsp.StatusCode != http.StatusOK {
		return fmt.Errorf("http status code is not ok [%v]", rsp.StatusCode)
	}
	rspbuf, err := ioutil.ReadAll(rsp.Body)
	if err != nil {
		return fmt.Errorf("read rsp body err, %v", err)
	}
	defer rsp.Body.Close()

	if err = api.ReadRsp(rspbuf, nil); err != nil {
		return fmt.Errorf("read rsp data err, %v", err)
	}
	return nil
}
